package com.yxsk.relay.job.admin.data.aop;

import com.yxsk.relay.job.admin.data.entity.BaseEntity;
import com.yxsk.relay.job.component.common.utils.DateUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.stream.Stream;

/**
 * @Author 11376
 * @CreaTime 2019/6/22 15:13
 * @Description
 */
@Component
@Aspect
public class EntityTimeHandler {

    @Pointcut("execution(* org.springframework.data.repository.CrudRepository.save*(..))")
    public void savePoint() {
    }

    @Around("savePoint()")
    public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        if (args != null) {
            Stream.of(args).forEach(o -> {
                if (o != null && o instanceof BaseEntity) {
                    BaseEntity entity = (BaseEntity) o;
                    setTime(entity);
                    setDelFlag(entity);
                }
            });
        }
        return joinPoint.proceed(args);
    }

    private void setDelFlag(BaseEntity entity) {
        if (entity.getDelFlag() == null) {
            entity.setDelFlag(BaseEntity.DelFlagEnum.NORMAL.getFlag());
        }
    }

    private void setTime(BaseEntity entity) {
        Date now = DateUtils.getCurrentDate();
        entity.setCreateTime(entity.getCreateTime() == null ? now : entity.getCreateTime());
        entity.setUpdateTime(now);
    }

}
